/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.sd.service;

import com.alibaba.fastjson.JSON;
import com.google.zxing.WriterException;
import com.itextpdf.text.DocumentException;
import com.jeesite.common.codec.AesUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Extend;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.sd.common.constants.DocLogEnum;
import com.jeesite.modules.sd.common.constants.GlobalEnum;
import com.jeesite.modules.sd.common.constants.RecvConstant;
import com.jeesite.modules.sd.common.util.DateUtils;
import com.jeesite.modules.sd.common.util.LogUtil;
import com.jeesite.modules.sd.common.vo.DocUrge;
import com.jeesite.modules.sd.dao.DocDeliverRecordDao;
import com.jeesite.modules.sd.dao.DocRecvDao;
import com.jeesite.modules.sd.entity.*;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.print.PrintException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 文件复制Service
 *
 * @author ysj
 * @version 2020-07-01
 */
@Service
@Transactional(readOnly = true)
public class DocDeliverRecordService extends CrudService<DocDeliverRecordDao, DocDeliverRecord> {
    @Autowired
    private DocRecvService docRecvService;
    @Autowired
    private DocDeliverRecordDao docDeliverRecordDao;
    @Autowired
    private DocRecvDao docRecvDao;
    @Autowired
    private UserService userService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private PrintService printService;
    /**
     * 获取单条数据
     *
     * @param docDeliverRecord
     * @return
     */
    @Override
    public DocDeliverRecord get(DocDeliverRecord docDeliverRecord) {
        return super.get(docDeliverRecord);
    }

    /**
     * 查询分页数据
     *
     * @param docDeliverRecord 查询条件
     * @param
     * @return
     */
    @Override
    public Page<DocDeliverRecord> findPage(DocDeliverRecord docDeliverRecord) {
        return super.findPage(docDeliverRecord);
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param docDeliverRecord
     */
    @Override
    @Transactional(readOnly = false)
    public void save(DocDeliverRecord docDeliverRecord) {

        super.save(docDeliverRecord);
    }

    /**
     * 拟办正常领文功能
     * doi 拟办记录的Id
     * id 来文Id
     */
    @Transactional(readOnly = false)
    public void takeFile(String id, String doi, User user) {
        DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
        docDeliverRecord.setId(doi);
        docDeliverRecord.setTakeDate(new Date());
        docDeliverRecord.setTakeUserCode(user.getUserCode());
        docDeliverRecord.setTakeUserName(user.getUserName());
        docDeliverRecord.setTakeUserPoliceno(user.getExtend().getExtendS1());
        docDeliverRecordDao.takeDocFile(docDeliverRecord);
        DocRecv docRecv = docRecvService.get(id);
        //存储日志信息
        LogUtil.LogInsert(id, docRecv.getDocTitle(), docRecv.getDocFullNum(), "拟办文件领取", docRecv.getSecLvl(), DocLogEnum.DOC_LOG_TYPE_PROPOSED);

    }

    /**
     * 拟办临时领文
     * @param id 来文记录表的id
     * @param docId 收文表中的文件id
     * @param userName 用户姓名
     * @param userPolice 用户警号
     */
    @Transactional(readOnly = false)
    public void temporaryTakeFile(String id, String docId, String userName,String userPolice,String face) {
        DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
        docDeliverRecord.setId(id);
        docDeliverRecord.setTakeDate(new Date());
        docDeliverRecord.setTakeUserName(userName);
        docDeliverRecord.setTakeUserPoliceno(userPolice);
        docDeliverRecord.setTakeUserFace(face);
        docDeliverRecordDao.takeDocFile(docDeliverRecord);
        DocRecv docRecv = docRecvService.get(docId);
        //存储日志信息
        LogUtil.LogInsert(id, docRecv.getDocTitle(), docRecv.getDocFullNum(), "拟办文件领取", docRecv.getSecLvl(), DocLogEnum.DOC_LOG_TYPE_PROPOSED);

    }

    /**
     *
     * 拟办正常还文功能
     *
     * @param id  来文表id
     * @param doi 来文记录表id
     * @param user 用户对象
     */
    @Transactional(readOnly = false)
    public void returnFile(String id, String doi, User user) {
        DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
        docDeliverRecord.setId(doi);
        docDeliverRecord.setReturnDate(new Date());
        docDeliverRecord.setReturnUserCode(user.getUserCode());
        docDeliverRecord.setReturnUserName(user.getUserName());
        docDeliverRecord.setReturnUserPoliceno(user.getExtend().getExtendS1());
        try{
            docDeliverRecordDao.returnDocFile(docDeliverRecord);
        }catch (Exception e){
            logger.error("文件归还时数据出错");
        }

        DocRecv DocRecv = new DocRecv();
        DocRecv.setId(id);
        docRecvDao.updateFileState(DocRecv);
        DocRecv docRecv = docRecvService.get(id);
        //存储日志信息
        LogUtil.LogInsert(id, docRecv.getDocTitle(), docRecv.getDocFullNum(), "拟办文件归还", docRecv.getSecLvl(), DocLogEnum.DOC_LOG_TYPE_PROPOSED);
    }

    /**
     *通过机构编码搜索该机构下面的员工
     * @param officeCode
     * @return
     */
    @Transactional(readOnly = false)
   public  List<Employee> searchUserByOffice(String officeCode){
        List<Employee> empUsers = docDeliverRecordDao.searchUserByOffice(officeCode);
        return empUsers;
    }
    /**
     * 拟办临时还文
     * @param userName
     * @param polioce
     * @param docId
     * @param id
     */
    @Transactional(readOnly = false)
    public void temporaryReturnFile(String userName, String polioce, String docId,String id,String face) {
        DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
        docDeliverRecord.setId(id);
        docDeliverRecord.setReturnDate(new Date());
        docDeliverRecord.setReturnUserName(userName);
        docDeliverRecord.setReturnUserPoliceno(polioce);
        docDeliverRecord.setReturnUserFace(face);
        docDeliverRecordDao.returnDocFile(docDeliverRecord);
        DocRecv DocRecv = new DocRecv();
        DocRecv.setId(docId);
        docRecvDao.updateFileState(DocRecv);
        DocRecv docRecv = docRecvService.get(docId);
        //存储日志信息
        LogUtil.LogInsert(docId, docRecv.getDocTitle(), docRecv.getDocFullNum(), "拟办文件归还", docRecv.getSecLvl(), DocLogEnum.DOC_LOG_TYPE_PROPOSED);
    }

    /**
     * 修改原文的状态为待分发
     *
     * @param docDeliverRecord
     * @param
     */
    @Transactional(readOnly = false)
    public void updateState(DocDeliverRecord docDeliverRecord) {
        Date returnDate = docDeliverRecord.getReturnDate();
        if (returnDate != null) {
            String id = docDeliverRecord.getDocId();
            if (StringUtils.isNotEmpty(id)) {
                DocRecv docRecv = new DocRecv();
                docRecv.setId(id);
                DocRecv docRecv1 = docRecvService.get(docRecv);
                if (docRecv1 != null) {
                    int docStatus = Integer.parseInt(docRecv1.getDocStatus());
                    if (docStatus != 0) {
                        docRecv1.setDocStatus("0");
                        docRecvService.save(docRecv1);
                    }

                }

            }
        }
        super.save(docDeliverRecord);
    }

    /**
     * 更新状态
     *
     * @param docDeliverRecord
     */
    @Override
    @Transactional(readOnly = false)
    public void updateStatus(DocDeliverRecord docDeliverRecord) {
        super.updateStatus(docDeliverRecord);
    }

    /**
     * 删除数据
     *
     * @param docDeliverRecord
     */
    @Override
    @Transactional(readOnly = false)
    public void delete(DocDeliverRecord docDeliverRecord) {
        super.delete(docDeliverRecord);
    }

    /**
     * 通过原文id查询是否有拟办/分发记录
     *
     * @param id
     * @return
     */
    public boolean hasRecord(String id) {

        int count = dao.getRecordCountByDocIdAndType(id);
        return count != 0;

    }


    /**
     * 通过单位编号和领取人姓名,警号,脸部识别路径领取文件(临时领文)
     *
     * @param officeCode       单位编号
     * @param takeUserName     姓名
     * @param takeUserPoliceNo 警号
     * @param takeUserFace     脸部识别路径
     * @param userCode         临时领文用户id为空
     * @throws RuntimeException 通过exception.getMessage()可获取异常信息
     */
    @Transactional(readOnly = false)
    public void takeDoc(String officeCode, String takeUserName, String takeUserPoliceNo, String takeUserFace, String userCode) {
        //判断当前单位是否为领文单位
        Office currOffice = officeService.get(officeCode);
        if (Objects.isNull(currOffice)) {
            //!currOffice.getExtend().getExtendS1().equals(GlobalEnum.OFFICE_TYPE_GET.getKey())
            logger.error("单位Code:{},不是领文单位!", officeCode);
            throw new RuntimeException("没有此领文单位!");

        }
        //查询当前单位存储在信箱的待领文件
        List<DocDeliverRecord> records = selectWaitRecordByOfficeCode(officeCode);
        //判断是否有可领取文件
        if (CollectionUtils.isEmpty(records)) {
            logger.error("单位名称:{},无可领取文件!", currOffice.getOfficeName());
            throw new RuntimeException("没有可领取的文件!");
        }
        //领文时间
        Date takeDate = new Date();

        try {
            records.forEach(record -> {
                record.setTakeDate(takeDate);
                record.setTakeUserName(takeUserName);
                record.setTakeUserPoliceno(takeUserPoliceNo);
                record.setTakeUserFace(takeUserFace);
                record.setTakeUserCode(userCode);
                //更新记录
                dao.update(record);
                DocRecv docRecv = docRecvService.get(record.getDocId());
                //记录文件领取日志
                LogUtil.insertLog(docRecv,
                        currOffice.getOfficeName()+"领取文件,领文人:"+takeUserName+"警号:"+takeUserPoliceNo,
                        DocLogEnum.DOC_LOG_TYPE_DELIVER);
            });

        } catch (Exception e) {
            logger.error("文件领取时保存数据出错,错误信息:",e);
            throw new RuntimeException("操作失败,保存文件信息出错!");
        }

    }

    /**
     * 通过单位编号和用户ID领取文件(系统中有该用户情况领文)
     *
     * @param officeCode 单位编号
     * @param userCode   领取用户ID
     * @throws RuntimeException 通过exception.getMessage()可获取异常信息
     */
    @Transactional(readOnly = false)
    public void takeDoc(String officeCode, String userCode) {
        User user = userService.get(userCode);
        if (Objects.isNull(user)) {
            logger.error("领取文件时查询无用户,userCode:{}", userCode);
            throw new RuntimeException("没有此用户!");
        }
        String takeUserName = user.getUserName();
        String takeUserPoliceNo = user.getExtend().getExtendS1();
        String takeUserFace = user.getExtend().getExtendS3();
        takeDoc(officeCode, takeUserName, takeUserPoliceNo, takeUserFace, userCode);
    }


    /**
     * 通过recordId 用户id 归还文件(系统中有该用户)
     *
     * @param recordId 文件id
     * @param userCode 用户id
     * @throws RuntimeException 通过exception.getMessage()可获取异常信息
     */
    @Transactional(readOnly = false)
    public void returnDoc(String recordId, String userCode) {
        User user = userService.get(userCode);
        if (Objects.isNull(user)) {
            logger.error("归还文件时查询无用户,userCode:{}", userCode);
            throw new RuntimeException("没有此用户!");
        }
        String returnUserName = user.getUserName();
        String returnUserPoliceNo = user.getExtend().getExtendS1();
        String returnUserFace =user.getExtend().getExtendS3();
        returnDoc(recordId, returnUserName, returnUserPoliceNo, returnUserFace, userCode);
    }

    /**
     * 临时还文
     *
     * @param recordId           文件id
     * @param returnUserName     还文人姓名
     * @param returnUserPoliceNo 还文人警号
     * @param returnUserFace     还文人脸部识别路径
     * @param userCode           临时还文用户id为空
     * @throws RuntimeException 通过exception.getMessage()可获取异常信息
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void returnDoc(String recordId, String returnUserName, String returnUserPoliceNo, String returnUserFace, String userCode) {
        DocDeliverRecord returnRecord = get(recordId);
        if (Objects.isNull(returnRecord)) {
            throw new RuntimeException("没有此文件相关信息!");
        }
        //获取来文文件信息
        DocRecv docRecv = docRecvService.get(returnRecord.getDocId());
        if (Objects.nonNull(returnRecord.getReturnDate())) {
            throw new RuntimeException(docRecv.getDocFullNum()+"当前文件已经归还!");
        }

        returnRecord.setReturnDate(new Date());
        returnRecord.setReturnUserName(returnUserName);
        returnRecord.setReturnUserPoliceno(returnUserPoliceNo);
        returnRecord.setReturnUserFace(returnUserFace);
        returnRecord.setReturnUserCode(userCode);
        //更新文件状态
        try {
            dao.update(returnRecord);
            //记录日志
            LogUtil.insertLog(docRecv,
                    returnRecord.getOffice().getOfficeName()+"归还文件,还文人:"+returnUserName+"警号:"+returnUserPoliceNo,
                    DocLogEnum.DOC_LOG_TYPE_DELIVER);
        } catch (Exception e) {
            logger.error("领取文件保存信息出错,错误信息:",e);
            throw new RuntimeException("保存文件信息出错!");
        }


    }

    /**
     * 批量归还文件信息
     * @param user 还文人信息
     * @param ids 还文列表
     */
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public void batchReturnDoc(User user, String[] ids) {
        //还文清单
        Checklist checklist = new Checklist();
        User optUser = UserUtils.getUser();
        //记录还文人操作人信息
        checklist.setOptUserName(optUser.getUserName())
                .setOptUserPoliceNo(optUser.getExtend().getExtendS1())
                .setReturnUserName(user.getUserName())
                .setReturnUserPoliceNo(user.getExtend().getExtendS1())
                //设置还文人的单位信息
                .setUnitName(get(ids[0]).getOffice().getOfficeName())
                //获取当前时间中文格式
                .setReturnDate(DateUtils.String.currDateTimeChinese());

        //用户id为空则为临时还文
        Arrays.stream(ids).forEach(id -> returnDoc(id,
                user.getUserName(),
                user.getExtend().getExtendS1(),
                user.getExtend().getExtendS3(),
                user.getUserCode()));

        //将还文信息记录到还文清单中
        List<ReturnFileInfo> infos = dao.getReturnFileInfoByRecordId(ids);
        checklist.setFileInfos(infos);

        //打印清单信息
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            printService.printCheckList(checklist,outputStream);
        } catch (IOException | DocumentException e) {
            logger.error("打印二维码出错,错误信息:",e);
            throw new RuntimeException("系统错误,请联系开发人员!");
        } catch (PrintException e) {
            logger.error("打印二维码出错,错误信息:",e);
            throw new RuntimeException("打印机连接失败!");
        }

    }

    /**
     * 通过单位code查询待领取文件
     *
     * @param officeCode 单位code
     * @return 待领取文件
     */
    public List<DocDeliverRecord> selectWaitRecordByOfficeCode(String officeCode) {
        return dao.selectWaitRecordByOfficeCode(officeCode);
    }

    /**
     * 领文回显
     * @param id 机构
     * @return 查出来的文件集合
     */
    public List<DocDeliverRecord> getTakeFileInfor(String id){
        List<DocDeliverRecord> takeFileInfor = docDeliverRecordDao.getTakeFileInfor(id);

        return  takeFileInfor;
    }
    /**
     * 通过信箱编码查询对应的单位编码
     *
     * @param boxNumber 信箱编码
     * @return 单位编码
     */
    public String selectOfficeCodeByBoxNumber(String boxNumber) {
        return dao.selectOfficeCodeByBoxNumber(boxNumber);
    }

    /**
     * 通过docId查询分发的单位信息
     *
     * @param id docId
     * @return 分发单位信息
     */
    public List<Office> getSendUintByDocId(String id) {
        return dao.getSendUintByDocId(id);
    }

    /**
     * 打印单个复印件的二维码
     * @param record 复印件信息
     */
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public void printCode(DocDeliverRecord record) {
        printCodeByRecord(record);
    }

    /**
     * 通过复印件信息打印二维码
     * @param record record中需包含单位和原文信息
     */
    public void printCodeByRecord(DocDeliverRecord record){
        record = docDeliverRecordDao.get(record);
        StringBuilder letterBox = new StringBuilder("柜号：");
        //
        if(RecvConstant.DOC_BOX_NUMBER_ZERO.equals(record.getOffice().getExtend().getExtendS4())){
            // 信箱号
            letterBox.append("——(送文)");
        }else{
            letterBox.append(record.getOffice().getExtend().getExtendS4());
        }

        // 单位
        String unit = "单位：" + record.getOffice().getOfficeName();
        // 来文标题
        String fullNum = record.getDocRecv().getDocFullNum();
        // 输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        //TODO 规范二维码内容
        DocCodeDTO code = new DocCodeDTO();
        DocRecv docRecv = docRecvService.get(record.getDocRecv());
        code.setRecordId(record.getId())
                .setBeforeReturnDate(record.getBeforeReturnDate())
                .setDocTitle(docRecv.getDocTitle())
                .setSecLvl(docRecv.getSecLvl())
                .setDocSysCode(docRecv.getDocSysCode())
                .setDocFullNum(docRecv.getDocFullNum())
                .setUppUnitName(docRecv.getUppUnit().getUnitName())
                .setBoxNum(record.getOffice().getExtend().getExtendS4());
        String jsonCode = JSON.toJSONString(code);
        String key = Global.getConfig("doc.code.aeskey");
        if(StringUtils.isEmpty(key)){
            logger.error("二维码加密key为空");
            throw new RuntimeException("二维码加密key为空,请联系开发人员!");
        }
        String encodeJson = AesUtils.encode(jsonCode, key);
        try {
            printService.printCode(encodeJson, fullNum,
                    letterBox.toString(), unit, 32, outputStream);
        } catch (IOException | WriterException e) {
            logger.error("打印二维码出错,错误信息:",e);
            throw new RuntimeException("系统错误,请联系开发人员!");
        }  catch (PrintException e) {
            logger.error("打印二维码出错,错误信息:",e);
            throw new RuntimeException("未连接打印机!");
        }
    }

    /**
     * 通过文件id查询最大分发编号
     * @param recvId 文件id
     * @return 最大分发编号
     */
    public int findMaxCopyNoByRecvId(String recvId) {
        return dao.findMaxCopyNoByRecvId(recvId);
    }

    /**
     * 通过秘书处单位类型查询秘书处单位Code
     * @param key 单位类型
     * @return 秘书处单位Code
     */
    public String getSecretariatOfficeCode(String key) {
        return dao.getSecretariatOfficeCode(key);
    }

    /**
     * 获取秘书处领文人信息
     * @return null:没有用户 user:用户信息
     */
    public User getSecretariatUser(){
        EmpUser empUser = new EmpUser();
        empUser.getEmployee().getOffice().setIsQueryChildren(true);
        String officeCode = dao.getSecretariatOfficeCode(GlobalEnum.OFFICE_TYPE_SECRETARIAT.getKey());
        empUser.setCodes(new String[]{officeCode});
        List<EmpUser> list = empUserService.findUserListByOfficeCodes(empUser);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        return userService.get(list.get(0));
    }

    /**
     * 判断该单位是否存在
     * @param unitType 枚举
     * @return b
     */
    public boolean isExistOffice(String unitType){
        Office office = new Office();
        Extend extend = new Extend();
        extend.setExtendS1(unitType);
        office.setExtend(extend);
        List<Office> list = officeService.findList(office);
        return CollectionUtils.isNotEmpty(list);

    }


    /**
     * 查询超时的待领取文件
     * @return 超时文件list集合
     */
    public List<DocDeliverRecord> listOutTimeTakeRecord(){
        DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
        docDeliverRecord.getSqlMap().getWhere().and("take_date", QueryType.IS_NULL,null);
        docDeliverRecord.getSqlMap().getWhere().and("before_take_date",QueryType.LT, DateUtils.String.currDateTime());
        return findList(docDeliverRecord);
    }

    /**
     * 查询超时的待归还文件
     * @return 超时文件list集合
     */
    public List<DocDeliverRecord> listOutTimeReturnRecord(){
        DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
        docDeliverRecord.getSqlMap().getWhere().and("take_date", QueryType.IS_NOT_NULL,null);
        docDeliverRecord.getSqlMap().getWhere().and("return_date", QueryType.IS_NULL,null);
        docDeliverRecord.getSqlMap().getWhere().and("before_return_date",QueryType.LT, DateUtils.String.currDateTime());
        return findList(docDeliverRecord);
    }

    /**
     * 查询拟办待领取总数
     * @return 拟办待领取总数
     */
    public long countWaitTake() {
        DocDeliverRecord query = new DocDeliverRecord();
        query.getSqlMap().getWhere().and("deliver_type", QueryType.EQ, GlobalEnum.RECORD_DELIVER_TYPE_PROPOSED.getKey());
        query.getSqlMap().getWhere().and("take_date",QueryType.IS_NULL,null);
        return findCount(query);
    }

    /**
     * 查询拟办待归还总数
     * @return 拟办归还取总数
     */
    public long countWaitReturn() {
        DocDeliverRecord query = new DocDeliverRecord();
        query.getSqlMap().getWhere().and("deliver_type", QueryType.EQ, GlobalEnum.RECORD_DELIVER_TYPE_PROPOSED.getKey());
        query.getSqlMap().getWhere().and("take_date",QueryType.IS_NOT_NULL,null);
        query.getSqlMap().getWhere().and("return_date",QueryType.IS_NULL,null);
        return findCount(query);
    }

    /**
     * 查询已分发总数
     * @return 已分发总数
     */
    public long countDeliver() {
        DocDeliverRecord query = new DocDeliverRecord();
        query.getSqlMap().getWhere().and("deliver_type" , QueryType.IN
                , new String[]{GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey()
                        ,GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey()});
        return findCount(query);
    }

    /**
     * 查询已分发待领取总数
     * @return 已分发待领取总数
     */
    public long countDeliverWaitTake() {
        DocDeliverRecord query = new DocDeliverRecord();
        query.getSqlMap().getWhere().and("deliver_type" , QueryType.IN
                , new String[]{GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey()
                        ,GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey()});
        query.getSqlMap().getWhere().and("take_date",QueryType.IS_NULL,null);
        return findCount(query);
    }

    /**
     * 查询已分发待归还总数
     * @return 已分发待归还总数
     */
    public long countDeliverWaitReturn() {
        DocDeliverRecord query = new DocDeliverRecord();
        query.getSqlMap().getWhere().and("deliver_type" , QueryType.IN
                , new String[]{GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey()
                        ,GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey()});
        query.getSqlMap().getWhere().and("take_date",QueryType.IS_NOT_NULL,null);
        query.getSqlMap().getWhere().and("return_date",QueryType.IS_NULL,null);
        return findCount(query);
    }

    /**
     * 查询已分发待归还总数
     * @return 已分发待归还总数
     */
    public long countDeliverReturn() {
        DocDeliverRecord query = new DocDeliverRecord();
        query.getSqlMap().getWhere().and("deliver_type" , QueryType.IN
                , new String[]{GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey()
                        ,GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey()});
        query.getSqlMap().getWhere().and("take_date",QueryType.IS_NOT_NULL,null);
        query.getSqlMap().getWhere().and("return_date",QueryType.IS_NOT_NULL,null);
        return findCount(query);
    }


    /**
     * 来文角度进行统计
     * @param lwStart
     * @param lwEnd
     * @param testUserCode
     * @param lwSecLvl
     * @param lwEmergLvl
     * @return
     */
    @Transactional(readOnly = false)
    public int rescStatistics(String lwStart,String lwEnd,String[] testUserCode,String lwSecLvl,String lwEmergLvl,String lengthCode){

        return docDeliverRecordDao.rescStatistics(lwStart, lwEnd, testUserCode, lwSecLvl, lwEmergLvl,lengthCode);
   }

    /**
     * 分发角度
     * @param fenStart
     * @param fenEnd
     * @param testUserCode
     * @param takeUser
     * @param returnUser
     * @param lengthCode
     * @return
     */
    @Transactional(readOnly = false)
   public  int distribStatistics(String fenStart, String fenEnd, String[] testUserCode, String takeUser, String returnUser, String lengthCode){

        return  docDeliverRecordDao.distribStatistics(fenStart,fenEnd,testUserCode,takeUser,returnUser,lengthCode);
    }

    /***
     * 催领催还 统计
     * @param urgeStart
     * @param urgeEnd
     * @param recvCode
     * @return
     */
    @Transactional(readOnly = false)
    public DocUrge urgeTake(String urgeStart, String urgeEnd, String recvCode){

        return  docDeliverRecordDao.urgeTake(urgeStart,urgeEnd,recvCode);
    }

    /**
     * 销毁情况统计
     * @param destroyStart
     * @param destroyEnd
     * @return
     */
    @Transactional(readOnly = false)
    public int destoryStatistics(String destroyStart,String destroyEnd){
        return  docDeliverRecordDao.destoryStatistics( destroyStart, destroyEnd);
    }


}